package com.redwood.report.net;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Handler;

import com.redwood.report.common.Config;
import com.redwood.report.common.Constant;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/8/5.
 */
public class UpLoadImageUtil {
    private int httpConnectTimeout = 8000;
    private int httpReadTimeout = 8000;
    private String sessionCookie = "";
    private String recoResult = "";

    /**
     * 上传接口
     *
     * @author taoli
     * @since 2015-11-19 下午04:57:36
     */
    public void uploadPic(String filename, String url, Handler micImageHandler) throws IOException {
        String asrAddr = Constant.getBaseUrl() + url;
        postData(filename, asrAddr, micImageHandler);
    }

    /**
     * 上传数据到服务器
     *
     * @author taoli
     * @since 2015-11-19 下午04:57:36
     */
    private void postData(String filename, String url, Handler micImageHandler) throws IOException { //boolean isEnd, int failures, boolean isGetAsyncNlp
        byte[] data = getBytes(filename);
//        Log.i("supeng","size="+data.length/1024);
     //   Utils.bytesToImageFile(data);
        int count = data.length;
        int offset = 0;
        URL asrUrl = new URL(url);
        HttpURLConnection connection = null;
        int respCode = 0;
        try {
            connection = (HttpURLConnection) asrUrl.openConnection();
            connection.setConnectTimeout(httpConnectTimeout);
            connection.setReadTimeout(httpReadTimeout);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            // connection.setRequestProperty("User-Agent", "Java Client");
            connection.setFixedLengthStreamingMode(count);
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("Content-Length", String.valueOf(count));
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Authorization", Config.getUserInfo().getToken());
            connection.setUseCaches(false);
            if (sessionCookie.length() > 0) {
                connection.setRequestProperty("Cookie", sessionCookie);
            }
            connection.connect();
            //上传数据到服务器
            if (data != null && count > 0) {
                connection.getOutputStream().write(data, offset, count);
                connection.getOutputStream().flush();
            }
            //服务器返回值
            respCode = connection.getResponseCode();
            if (respCode == HttpURLConnection.HTTP_OK) {
                String key = "";
                String cookie = "";
                for (int i = 1; (key = connection
                        .getHeaderFieldKey(i)) != null; i++) {
                    if (key.equalsIgnoreCase("set-cookie")) {
                        cookie = connection.getHeaderField(key);
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    } else if (key.equalsIgnoreCase("s2s_service_version")) {
                    }
                }
                if (cookie.length() > 10) {
                    sessionCookie = cookie;
                }
                InputStream is = connection.getInputStream();
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    try {
                        String lines = "";
                        String line = null;
                        boolean hasResult = false;
                        while ((line = br.readLine()) != null) {
                            if (!hasResult) {
                                hasResult = true;
                            } else {
                                // lines += "\n";
                            }
                            lines += line;
                        }
                        recoResult = lines;
                        if (hasResult) {
                            android.os.Message msg = new android.os.Message();
                            Bundle bundle = new Bundle();
                            msg.setData(bundle);
                            bundle.putString("result", recoResult);
                            bundle.putString("filename",filename);
                            msg.what = 2;
                            micImageHandler.sendMessage(msg);
                        }
                    } finally {
                        br.close();
                    }
                } finally {
                    is.close();
                }
            }
        } catch (EOFException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            respCode = 1;
        } finally {

            if (connection != null)
                connection.disconnect();
        }
        if (respCode != HttpURLConnection.HTTP_OK) {
            sessionCookie = "";
            throw new IOException("HTTP retcode error: " + respCode);
        }
    }

    /**
     * 获得指定文件的byte数组
     * sp
     * 2016年5月26日10:16:32
     */
    public byte[] getBytes(String filePath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, newOpts);// 此时返回bm为空
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 设置固定分辨率，所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        } else if (w == h) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(filePath, newOpts);
        int degree = readPictureDegree(filePath);
        Bitmap newBitmap = rotatingImageView(degree, bitmap);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
        if (newBitmap != null) {
            newBitmap.recycle();
            System.gc();
        }
        return baos.toByteArray();// 压缩好比例大小后再进行质量压缩
    }

    /**
     *  获取图片旋转的角度
     * <p>
     *  @param path 图片的路径
     *  @return 返回旋转的角度值
     *      
     */
    public int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     *  旋转图片
     * <p>
     *  @param angle 图片旋转的角度
     * <p>
     *  @param bitmap
     *      
     */
    public Bitmap rotatingImageView(int angle, Bitmap bitmap) {
        if (angle == 0)
            return bitmap;
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = null;
        if (bitmap != null) {
            resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        return resizedBitmap;
    }
}
